import 'dart:async';
import 'dart:io';

import 'package:book_manager_app/app/utils/common/app_manager.dart';
import 'package:camera/camera.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:camera/camera.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
import 'package:just_audio/just_audio.dart';
import 'package:vibration/vibration.dart';

import '../../../theme/text_style.dart';
import '../../../utils/widget/common.dart';
import '../../add_book/models/book.dart';
import '../controllers/home_controller.dart';
import 'budget_list_view.dart';

// 全局音频播放器
AudioPlayer _player = AudioPlayer();

// 播放音频
playerAsset(String asset) async {
  _player.setAsset(asset);
  _player.seek(Duration.zero);
  _player.play();
}

// 震动提示
vibrate() async {
  if (await Vibration.hasVibrator() as bool) {
    Vibration.vibrate(duration: 100, amplitude: 255);
  }
}

class ScannerBookView extends StatefulWidget {
  MobileScannerController? scanner;
  final Function(MobileScannerController controller, String name, String value)? callBack;
  ScannerBookView({super.key, this.scanner, this.callBack});

  @override
  State<ScannerBookView> createState() => _ScannerBookViewState();
}

class _ScannerBookViewState extends State<ScannerBookView> with WidgetsBindingObserver {
  int nowPage = 0;
  double _zoomScale = 0;
  bool _first = true;
  double _lightLevel = 200; // 光线强度
  PageController pageController = PageController();
  late MobileScannerController scanController;

  String _modelType = "0";

  HomeController controller = Get.find();


  // 上次扫码时间
  DateTime? _lastScanTime;
  // 如果距离上次识别不到 2 秒，则忽略本次结果
  final Duration scanInterval = Duration(milliseconds: 1500);


  @override
  initState() {
    super.initState();
    // _startLightSensor();
    setupScanner();
  }

  setupScanner() {
    widget.scanner = MobileScannerController(
      // torchEnabled: true,
      // formats: [BarcodeFormat.qrCode]
      // facing: CameraFacing.front,
      // detectionSpeed: DetectionSpeed.normal
      detectionTimeoutMs: 300, // 扫码的检测超时时间，单位是毫秒。
      // returnImage: false,
    );
    scanController = widget.scanner!;
  }


  @override
  void dispose() {
    super.dispose();
    scanController.stop();
    scanController.dispose();
  }

  /// 二维码处理完毕回掉
  Future<void> _scanQrCode(BarcodeCapture capture) async {

    // 如果距离上次识别不到 2 秒，则忽略本次结果
    if (_lastScanTime != null && DateTime.now().difference(_lastScanTime!) < scanInterval) {
      return;
    }
    _lastScanTime = DateTime.now();

    // 声音提醒
    playerAsset("assets/scanner.mp3");

    // 震动提示
    vibrate();

    List<Barcode> barcodes = capture.barcodes;
    String? result;
    for (final barcode in barcodes) {
      result = barcode.rawValue??"";
      debugPrint('扫码成功，解析结果为：$result');
    }

    if (widget.callBack != null) {
      String name = ["出售", "补货"][(_first?0:1)];
      widget.callBack!(scanController, name, result!);
    } else {
      // 停止扫描
      scanController.stop();
      Get.back(result: result);
    }
  }

  @override
  Widget build(BuildContext context) {
    return buildScanner();
  }


  Widget buildScanner() {
    return Stack(
      children: [

        Container(
          color: Colors.black,
        ),

        _cameraView(MobileScanner(
          controller: scanController,
          onDetect: _scanQrCode,
        )),

        Positioned(
            left: 10, top: 50,
            child: IconButton(
                onPressed: ()=> Get.back(),
                icon: const Icon(Icons.close, size: 32, color: Colors.white)
            )
        ),

        // 手电筒
        _flashLightButton(),

        // 相册
        // Positioned(right: 25, bottom: 125, child: _album()),

        // 单件出售和套装出售
        // Positioned(left: 100, right: 100, top: 54, child: _buildModelTypeSegment()),
        
        // 出售按钮
        Positioned(right: 10, top: 50, child: saleButton()),

        // // 总计价格
        Positioned(right: 10, top: 100, child: totalPrice()),

        // 待出库清单
        Positioned(left: 10, top: 120, child: BudgetListView()),

        // 总计价格
        Positioned(bottom: 110, left: 10, right: 10, child: totalPrice()),

        // 底部按钮
        Positioned(bottom: 0, child: setupBottom()),
      ],
    );
  }

  saleButton() {
    return Obx(() => controller.bookSalesReqs.isNotEmpty 
      ? MaterialButton(
        color: Colors.red,
        child: Text("立即出售", style: TextStyle(color: Colors.white)),
        onPressed: ()=> controller.sale(),
      )
      : SizedBox.shrink()
    );
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    switch (state) {
      case AppLifecycleState.resumed:
      //在前台激活
        if (!scanController.autoStart) {
          scanController.start();
        }
        break;
      case AppLifecycleState.inactive:
        break;
      case AppLifecycleState.detached:
        break;
      case AppLifecycleState.paused:
      //在后台暂停
        scanController.stop();
        break;
      case AppLifecycleState.hidden: // flutter 3.13
        break;
    }
  }

  // 双击放大或缩小
  void _changeZoomScale() {
    if (_zoomScale == 0) {
      _zoomScale = 1;
    } else {
      _zoomScale = 0;
    }
    scanController.setZoomScale(_zoomScale);
  }

  // 双指捏合放大或缩小
  void _onScaleChange(ScaleUpdateDetails details) {
    _zoomScale = (details.scale / 10 * 6 - 0.6).clamp(0, 1);
    scanController.setZoomScale(_zoomScale);
  }


  // 扫描相册二维码
  Future<void> _scanLocalQrCode() async {
    List<AssetEntity>? qrCodes = await AssetPicker.pickAssets(
      context,
      pickerConfig: AssetPickerConfig(
          maxAssets: 1,
          specialPickerType: SpecialPickerType.wechatMoment,
          requestType: RequestType.common),
    );
    try {
      late File file;
      await qrCodes![0].file.then((value) => file = value!);
      // 开始解析相册选中的图片二维码
      final BarcodeCapture? result = await scanController.analyzeImage(file.path);
      for (final Barcode barcode in result!.barcodes) {
        _scanQrCode(result);
      }
    } catch (e) {
      debugPrint('Error: $e');
    }
  }

  _modelTypeChange(var value) {
    vibrate();
    setState(() {
      _modelType = value;
    });
  }

  _buildModelTypeSegment() {
    return CupertinoSlidingSegmentedControl(
      groupValue: _modelType,
      thumbColor: Colors.red,
      backgroundColor: Colors.black87,
      onValueChanged: (value)=> _modelTypeChange(value),
      children: {
        "0": Padding(
          padding: const EdgeInsets.fromLTRB(0, 10, 0, 10),
          child: Text('单件出售', style: _modelType== "0" ? whiteStyle() : greyStyle()),
        ),
        "1": Padding(
          padding: const EdgeInsets.fromLTRB(0, 10, 0, 10),
          child: Text('套装出售', style: _modelType== "1" ? whiteStyle() : greyStyle()),
        ),
      },
    );
  }

  // 手电筒
  Widget _flashLightButton() {
    if (_lightLevel < 100) {
      return Positioned(
          left: MediaQuery.of(context).size.width / 2 - 25,
          bottom: 165,
          child: GestureDetector(
            onTap: ()=> scanController.toggleTorch(),
            child: const Column(
              children: [
                Icon(Icons.flashlight_on_outlined, size: 44, color: Colors.white),
                SizedBox(height: 8),
                Text('轻触照亮', style: TextStyle(color: Colors.white, fontSize: 15))
              ],
            ),
          )
      );
    }
    return const SizedBox();
  }

  // 相册
  Widget _album() {
    return GestureDetector(
      onTap: _scanLocalQrCode,
      child: Column(
          children: [
            ClipOval(
                child: Container(
                    padding: const EdgeInsets.all(10),
                    color: const Color.fromRGBO(70, 70, 70, 1),
                    child: const Icon(Icons.image, color: Colors.white)
                )
            ),
            const SizedBox(height: 1),
            const Text('相册', style: TextStyle(color: Colors.white, fontSize: 11))
          ]),
    );
  }

  // 相机预览
  Widget _cameraView(MobileScanner scanner) {
    return GestureDetector(
        onDoubleTap: _changeZoomScale,
        onScaleUpdate: _onScaleChange,
        child: SizedBox(height: double.infinity, child: scanner));
  }


  setupBottom() {
    final isManager = AppManager.userInfo?.roles.contains("storeManager") ?? false;
    final left = EdgeInsets.fromLTRB(_first && isManager ? 82 : 0, 0, isManager ? 20 : 0, 0);
    final right = EdgeInsets.fromLTRB(0, 0, _first? 0 : 82, 0);
    final leftColor = _first ? Colors.white : Colors.grey;
    final rightColor = _first ? Colors.grey : Colors.white;

    return Container(
      width: MediaQuery.of(context).size.width,
      height: 108,
      color: Colors.black,
      padding: const EdgeInsets.fromLTRB(20, 15, 20, 0),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Stack(
            alignment: Alignment.center,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  createButton(title: "出售", padding: left, color: leftColor, onTap: () async {
                    _first = true;
                    vibrate();
                    setState(() { });
                  }),
                 if (isManager)  const SizedBox(width: 20),
                 if (isManager) createButton(title: "补货", padding: right, color: rightColor, onTap: () async {
                    _first = false;
                    vibrate();
                    setState(() { });
                  }),
                ],
              ),
            ],
          ),
          const SizedBox(height: 6),
          ClipOval(child: Container(width: 8, height: 8, color: Colors.white)),
        ],
      ),
    );
  }

  createButton({String? title, EdgeInsetsGeometry? padding, Color? color, GestureTapCallback? onTap}) {
    return GestureDetector(
        onTap: onTap,
        child: AnimatedContainer(
          duration: const Duration(milliseconds: 100),
          padding: padding,
          child: Text(title!, style: TextStyle(color: color, fontSize: 22)),
        )
    );
  }

  // 总价显示
  Widget totalPrice() {
    return Obx(() {
      if (controller.bookSalesReqs.isEmpty) {
        return const SizedBox.shrink();
      }
      
      // 分别统计出售和赠送的图书
      final saleBooks = controller.bookSalesReqs.where((book) => book.payType != 5).toList();
      final giftBooks = controller.bookSalesReqs.where((book) => book.payType == 5).toList();
      
      final saleCount = saleBooks.length;
      final giftCount = giftBooks.length;
      final totalAmount = saleBooks.fold<double>(0.0, (sum, book) => sum + (book.salePrice ?? 0.0));
      
      // 构建显示文本
      String displayText = '';
      if (saleCount > 0 && giftCount > 0) {
        displayText = '出售 $saleCount 本\n赠送 $giftCount 本\n合计：¥${totalAmount.toStringAsFixed(2)}元';
      } else if (saleCount > 0) {
        displayText = '出售 $saleCount 本\n合计：¥${totalAmount.toStringAsFixed(2)}元';
      } else {
        displayText = '赠送 $giftCount 本\n合计：¥0.00元';
      }
      
      return Container(
        padding: const EdgeInsets.symmetric(horizontal: 0),
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
          decoration: BoxDecoration(
            color: Colors.white.withOpacity(0.2),
            borderRadius: BorderRadius.circular(4),
          ),
          child: Text(
            displayText,
            style: const TextStyle(
              color: Colors.yellow,
              fontSize: 16,
              fontWeight: FontWeight.w500,
            ),
            textAlign: TextAlign.center,
          ),
        ),
      );
    });
  }

  // 获取光线的强度
  Future<void> _startLightSensor() async {
    CameraController? cameraController;
    try {
      debugPrint("开始获取光线的强度 ${DateTime.now()}");
      double lightLevel = 0.0;
      final cameras = await availableCameras();
      final camera = cameras.first;
      /// 使用相机判断光线的强弱，光线弱则显示手电筒按钮
      // 仅初始化相机，但不启动图像流
      cameraController = CameraController(camera, ResolutionPreset.medium);
      await cameraController.initialize();

      // 使用异步延迟来确保相机完全初始化后再启动光线传感器
      await Future.delayed(const Duration(seconds: 1));
      /// 使用Completer来等待lightLevel的计算完成
      final completer = Completer<double>();

      // 启动图像流
      cameraController.startImageStream((CameraImage image) async {
        // 获取一次图像后停止图像流
        cameraController?.stopImageStream();

        final int numPixels = image.planes[0].bytes.length;
        final int sumPixels = image.planes[0].bytes.reduce((a, b) => a + b);
        final double avgPixel = sumPixels / numPixels;
        // 将光线强度值（0-255）映射到合理的光照值（lux）
        lightLevel = (avgPixel / 255.0) * 1000;
        completer.complete(lightLevel);
      });

      final result = await completer.future;
      debugPrint("获取光线强度结束 ${DateTime.now()}");
      debugPrint("光线强度 = ${result.toString()}");

      setState(() {
        _lightLevel = lightLevel;
      });
    } catch (e) {
      debugPrint("Error in _startLightSensor: $e");
    } finally {
      // 确保相机资源被释放
      if (cameraController != null) {
        await cameraController.dispose();
        debugPrint("释放了cameraController");
      }

    }
  }
  
  
}
